﻿using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Read.API.Application.Command.MenuCommand;
using D.Medicalcare.Read.API.Dtos;
using MediatR;

namespace D.Medicalcare.Read.API.Application.Handler.MenuHandler
{
    /// <summary>
    /// 根据角色Id查询菜单角色关系表处理
    /// </summary>
    public class GetRoleMenuHandler : IRequestHandler<GetRoleMenuCommand, APIResult<List<RMDTO>>>
    {
        private readonly IBaseRepository<Role> roleRep;
        private readonly IBaseRepository<Menu> menuRep;
        private readonly IBaseRepository<RoleMenu> rmRep;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="roleRep"></param>
        /// <param name="menuRep"></param>
        /// <param name="rmRep"></param>
        public GetRoleMenuHandler(IBaseRepository<Role> roleRep, IBaseRepository<Menu> menuRep, IBaseRepository<RoleMenu> rmRep)
        {
            this.roleRep = roleRep;
            this.menuRep = menuRep;
            this.rmRep = rmRep;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">命令</param>
        /// <returns>APIResult</returns>
        public Task<APIResult<List<RMDTO>>> Handle(GetRoleMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<RMDTO>> result = new APIResult<List<RMDTO>>();
            result.Code = APIEnum.Success;
            result.Msg = "查询成功";
            var m = from a in roleRep.GetAll()
                    join b in rmRep.GetAll() on a.RoleId equals b.RoleId
                    join c in menuRep.GetAll() on b.MenuId equals c.MenuId
                    where b.RoleId == request.RoleId
                    select new RMDTO
                    {
                        RMId = b.RMId,
                        RoleId = a.RoleId,
                        MenuId = b.MenuId,
                        RoleName = a.RoleName,
                        MenuName = c.MenuName,

                    };
            result.Data = m.ToList();
            return Task.FromResult(result);

        }
    }
}
